<?php

namespace Api\Controller;

use Think\Controller;
use \Common\Lib\Sms\Sms;
class ApiController extends Controller {

    protected $data = [];
    protected $callback = '';
    protected $authen = '';
    protected $user_info = null;
    protected $error = null;
    protected $page = 1;
    protected $page_size = 10;
    protected $setting;
    protected $http;
    protected $token = '';
    protected $source = '';


    public function __construct() {
        define('TIME', time());
        $this->data = I();
        $this->setting = C('setting');
        $this->callback = I('get.callback');
        $this->authen = $_SERVER['HTTP_X_USER_AUTHEN'];
        $this->token = $_SERVER['HTTP_X_TOKEN'];
        $this->source = $_SERVER['HTTP_X_SOURCE'];

        $this->initSetting();
        $this->checkAuthen();
        if ($this->data['page']) {
            $this->page = intval($this->data['page']);
        }
        $this->http = $_SERVER['SERVER_PORT']==443?'https':'http';
    }

    public function success($data = [], $message = '', $extras = []) {
        $return = [
            'data' => $data,
            'message' => $message,
            'extras' => $extras,
            'timestamp' => TIME,
            'path' => MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME,
        ];

        $return = json_encode(['success' => $return], JSON_UNESCAPED_UNICODE);
        if ($this->callback) {
            exit($this->callback . '(' . $return . ')');
        } else {
            exit($return);
        }
    }

    public function error($message, $code = '0000') {
        $return = json_encode(['error' => ['code' => $code, 'message' => $message, 'timestamp' => $_SERVER['REQUEST_TIME'],
                'path' => MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME,]], JSON_UNESCAPED_UNICODE);
        if ($this->callback) {
            exit($this->callback . '(' . $return . ')');
        } else {
            exit($return);
        }
    }

    /**
     * 检测用户登陆信息
     */
    protected function checkAuthen() {
//        if($this->source != '_818UP_COM'){
//            exit('');
//        }
        if(empty($this->authen)){
            $this->error='请先登录'; //解析失败,过期
            return null;
        }
        
        list($id, $password) = explode("\t", authcode($this->authen));
        if (!$id || !$password) {
            $this->error='请先登录'; //解析失败,过期
            return null;
        }
        
        $user_info = M('User')->find($id);
//        if($user_info['token'] != $this->token){
//            $this->error = '您的账号在异地登录';
//            return null;
//        }

        if (!$user_info) {
            $this->error='用户不存在';
            return null;
        }
        if ($user_info['available'] == 0) {
            $this->error='该用户已被禁止登录';
            return null;
        }
        if ($user_info['status'] == 0) {
            $this->error='该用户暂未激活';
            return null;
        }
        if ($user_info['password'] != $password) {
            $this->error='登录密码不正确';
            return null;
        }
        
        $this->user_info = $user_info;
    }

    /**
     * 完整地址
     */
    protected function full_url($url) {
        if (substr($url, 0, 4) == 'http') {
            return $url;
        } else {
            return 'http://' . $_SERVER['HTTP_HOST'] . '/' . ltrim($url, '/');
        }
    }

    /**
     * 返回会员信息
     */
    protected function loginAuth($uid) {
        if (!$uid) {
            return;
        }
        
        $user_info = M('User')->find($uid);
        
        $user_data = [];
        if ($user_info) {
            $authcode = authcode($user_info['id'] . "\t" . $user_info['password'], 'ENCODE');                        
            $user_data = $user_info;
            unset($user_data['password']);
            $user_data['authen'] = $authcode;
        }
        return $user_data;
    }

    //初始化配置
    protected function initSetting() {
        $this->setting['withdraw_day'] = intval($this->setting['withdraw_day']);

        if (!$this->setting['withdraw_day']) {    //提现次数
            $this->setting['withdraw_day'] = 1;
        }
        
        //最低提现金额
        if(!$this->setting['min_withdraw']){
            $this->setting['min_withdraw'] = 50;
        }
        
        // 圈子提成比例
        if(!$this->setting['circle_charge']){
            $this->setting['circle_charge'] = 10;
        }
    }

    //验证是否实名认证
    public function check_is_validate($tag = false){
        if(!$this->user_info){
            if($tag === false){
                $this->error('请先登录');
            }else{
                return false;
            }
        }
        
        $validate = M('User')->find($this->user_info['id']);
        if($validate['is_validate'] == 1){
            if($tag === false){
                $this->success(array(),'ok');
            }else{
                return true;
            }
        }else{
            if($tag === false){
                $this->error($this->user_info['nickname'].' 未经过实名认证');
            }else{
                return false;
            }
        }        
    }
    
    //随机名称
    protected function make_rand_name(){
        return uniqid().date(s);
    }
    
    //阿里云oss存储
    public function ali_oss_upload(array $file, $dir_name = 'dir/'){
        
        if(empty($file) || !is_array($file)){
            return false;
        }
        
        $tmp = $file['tmp_name'];
        list($pic,$ext) = explode('.', $file['name']);
        $new_name = $this->make_rand_name().'.'.$ext;
        
        $Ali = A('AliUpdate');
        if($Ali->putObject($dir_name.$new_name, $tmp) !== false){
            return $this->http.'://'.$this->setting['OSS_BUCKET'].'.'.$this->setting['OSS_ENDPOINT_OUTSIDE'].'/'.$dir_name.$new_name;
        }else{
            return false;
        }        
    }
    
    //删除OSS对象
    //@para $path  string  dir/objectname
    protected function ali_oss_unlink($path){
        if(empty($path)){
            return false;
        }
        
        $Ali = A('AliUpdate');
        if($Ali->doesObjectExist($path) === true){
            if($Ali->deleteObject($path)){
                return true;
            }
        }
        return false;
    }
    
    //图片上传,ajax
    /*
     * 异步传图片
     * 防止图片冗余上传，写入一个附件表
     */
    public function uploadImageAjax() {
        
        $file_name = I('get.photo','thumb');
        if(empty($file_name)){
            $this->error('没有指定上传的图片');
        }

        if(!$this->user_info){
            $this->error('没有权限操作');
        }
        
        /*oss 云开始*/
        $dir_name = 'dir/';
        
        $file = $_FILES[$file_name];
        if($file['size'] > 2097152){
            $this->error('图片超过最大限制2M');
        }
        //判断图片格式问题

        $photo = $this->ali_oss_upload($file, $dir_name);
        
        if($photo !== false){
            $this->success(array(),'上传成功',array('url'=>$photo));
        }
        $this->error('文件上传失败');
        /*oss 云结束*/
    }
    
    //注册发送短信
    public function send_sms(){
//        if(IS_AJAX){
        $mobile = I('post.mobile');
        $ck = I('ck',0,'intval');
        $cache = 'sms_send_'.$mobile;
        if(isMobile($mobile)){
            if(!S($cache)){
                //验证手机是否已使用
                $has_reg = M('User')->where(array('mobile'=>$mobile))->count();
                if($ck == 0){
                    //手机注册、手机认证
                    if($has_reg > 0){
                        $this->error($mobile.'手机号已使用过');
                    }
                }else{
                    //找回密码
                    if($has_reg < 1){
                        $this->error('该用户不存在');
                    }
                }

                $code = mt_rand(111111, 999999);
                S('sms_'.$mobile, $code, 180);  //记录验证码
                $msg = "【大行情】用户验证码{$code}，有效期3分钟";

                $result = json_decode(Sms::send($mobile, $msg),true);

                if($result['status'] == 'success'){
                    S($cache,time(),60);    //防止过于频繁发送短信   
                    S('get_sms_'.$mobile, $mobile, 180);  //记录接收验证码的手机号
                    $this->success([],"短信已发送至{$mobile}");
                }
                file_put_contents('./sms_error.txt', $result['errmsg'],FILE_APPEND);
                $this->error('短信发送失败'.$result['status']);
            }else{
                $this->error('发送短信过于频繁，稍微再试');
            }
        }
        $this->error('手机号格式错误');
        
    }
    
    //注册发送邮件
    protected function send_mail($to, $content=''){
        
        if(empty($to) || empty($content)){
            return false;
        }
        
        try {
            $mail = new \Common\Lib\Mail\PHPMailer(true);             
            $mail->IsSMTP(); 
            $mail->CharSet='UTF-8'; //设置邮件的字符编码，这很重要，不然中文乱码 
            $mail->SMTPAuth = true; //开启认证 
            $mail->Port = 25; 
            $mail->Host = $this->setting['smtp']; 
            $mail->Username = $this->setting['mail_address']; 
            $mail->Password = $this->setting['mail_password']; 
            //$mail->IsSendmail(); //如果没有sendmail组件就注释掉，否则出现“Could not execute: /var/qmail/bin/sendmail ”的错误提示 
            $mail->AddReplyTo($this->setting['mail_address'],"大行情");//回复地址 
            $mail->From = $this->setting['mail_address']; 
            $mail->FromName = $this->setting['site_name']; 
            $to = $to; 
            $mail->AddAddress($to); 
            $mail->Subject = $this->setting['site_name']; 
            $mail->Body = $content; 
            $mail->AltBody = "你的邮件不支持Html格式"; //当邮件不支持html时备用显示，可以省略 
            $mail->WordWrap = 80; // 设置每行字符串的长度 
            $mail->IsHTML(true); 
            $mail->Send(); 
            return true;
//            echo '邮件已发送'; 
        } catch (\Exception $e) {
            file_put_contents('./mail_error.log', $e->getMessage(), FILE_APPEND);
            return false;            
//            echo "邮件发送失败：".$e->errorMessage(); 
        } 
        
    }

    //获取用户协议=
    public function agreement(){
        $id = I('id',0,'intval');
        if(empty($id)){
            $id = 41;
        }
        $article = M('ArticlePage')->where(array('id'=>$id))->find();

        if(!empty($article)){
            $article['content'] = htmlspecialchars_decode(stripslashes($article['content']));
            $this->success($article,'');
        }
        $this->error('没有数据');
    }

    //APP关于我们
    public function about(){
        $id = I('id',0,'intval');
        if(empty($id)){
            $id = 48;
        }
        $article = M('ArticlePage')->where(array('id'=>$id))->find();

        if(!empty($article)){
            $article['content'] = htmlspecialchars_decode(stripslashes($article['content']));
            $this->success($article,'');
        }
        $this->error('没有数据');
    }
    
    // 检测输入的验证码是否正确，$code为用户输入的验证码字符串
    function check_verify($code, $id = ''){
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }

    //公用方法
    public function treeCategory(array $arr, $selected = 0) {
        if(!is_array($arr) || empty($arr)){
            return;
        }

        $Tree = new \Common\Lib\Tree($arr);
        $html = "<option data-type='\$type' value='\$id' \$selected>\$spacer \$name</option>";
        $result = $Tree->get_tree(0, $html, $selected, '&nbsp;&nbsp;&nbsp;&nbsp;');
        return $result;
    }
}
